<template>
  <div class="domain-creation-container">
    <!-- 标题 -->
    <h3 class="creation-title">新建主题域</h3>

    <!-- 表单区域 -->
    <el-form :model="newDomainForm" label-width="80px">
      <!-- 主题域名称输入 -->
      <el-form-item label="主题域名称">
        <el-input v-model="newDomainForm.name" placeholder="请输入主题域名称" clearable />
      </el-form-item>

      <!-- 操作按钮 -->
      <el-form-item>
        <el-button type="primary" @click="handleSave">保存</el-button>
        <el-button @click="handleCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { ElMessage } from "element-plus";
import IndicatorDomainAPI, { DomainGroupInsertParameter } from "@/api/indicationManage/domain";

const props = defineProps<{
  dataSourceId: 0;
}>();

const themeDomainInsertForm = reactive<DomainGroupInsertParameter>({
  dataSourceId: 0,
  domainName: "",
  domainType: 1,
  parentId: 0,
});

// 定义事件
const emit = defineEmits(["save", "cancel"]);

// 表单数据
const newDomainForm = ref({
  name: "", // 主题域名称
});

/**
 * 保存操作
 */
const handleSave = async () => {
  if (!newDomainForm.value.name) {
    ElMessage.error("请填写主题域名称");
    return;
  }

  try {
    themeDomainInsertForm.dataSourceId = props.dataSourceId;
    themeDomainInsertForm.domainName = newDomainForm.value.name;
    themeDomainInsertForm.domainType = 1;
    themeDomainInsertForm.parentId = 0;
    const result = await IndicatorDomainAPI.GroupInsert(themeDomainInsertForm);
    ElMessage.success("主题域新建成功");
    // 触发保存事件，传递完整的主题域数据以刷新菜单列表
    emit("save", {
      name: newDomainForm.value.name,
      // id: result.data.id,
      dataSourceId: props.dataSourceId,
    });

    // 清空表单
    newDomainForm.value.name = "";

    // 检查result是否存在且有data属性
    // if (result && result.data) {
    // } else {
    //   ElMessage.error("主题域新建失败：返回数据格式不正确");
    //   console.error("API返回结果异常:", result);
    // }
  } catch (error) {
    ElMessage.error(`主题域新建失败：${error instanceof Error ? error.message : String(error)}`);
    console.error("新建主题域时发生错误:", error);
  }
};

/**
 * 取消操作
 */
const handleCancel = () => {
  // 触发取消事件
  emit("cancel");

  // 清空表单
  newDomainForm.value.name = "";
};
</script>

<style scoped lang="scss">
.domain-creation-container {
  padding: 24px;
  background: var(--el-bg-color);
  border-radius: 8px;
  box-shadow: var(--el-box-shadow-light);
}

.creation-title {
  margin-bottom: 24px;
  font-size: 18px;
  font-weight: 500;
  color: var(--el-text-color-primary);
}

.el-form {
  max-width: 500px;
  margin: 0 auto;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-input {
  width: 100%;
}

.el-button {
  margin-right: 12px;
}
</style>
